package rrrmai.repository;

import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Room;
import android.util.Log;

import org.reactivestreams.Publisher;

import java.util.List;
import java.util.concurrent.Callable;

import javax.inject.Inject;
import javax.inject.Singleton;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import rrrmai.model.Rsp;
import rrrmai.room.dao.PostDao;
import rrrmai.room.database.AppDataBase;
import rrrmai.service.APIService;
import rrrmai.service.PostService;
import rrrmai.viewbinder.Post;

/**
 * Created by az on 2018/3/20.
 */

@Singleton
public class PostRepository extends Repository{
    //cache
    APIService mAPIService;
    AppDataBase mAppDataBase;

    @Inject
    public PostRepository(APIService mAPIService,AppDataBase mAppDataBase){
            this.mAPIService=mAPIService;
            this.mAppDataBase=mAppDataBase;
    }

    public Flowable<List<Post>> getPostList(int page, int pageSize) {
        return mAPIService.getService(PostService.class)
                .getPostList(page,pageSize)
                .flatMap(listRsp -> Flowable.fromArray(listRsp.getData()))
               .flatMap(posts -> inserPost(posts))
               .flatMap(rows ->mAppDataBase.postDao().loadAll());
    }



    private  Flowable<Long[]> inserPost(List<Post> posts){
        return Flowable.fromCallable(() -> mAppDataBase.postDao().insertPostList(posts));
    }

    public Long[] insert(Post ... post) {
          return mAppDataBase.postDao().insertPost(post);
    }

    public int delete(Post ... post) {
        return mAppDataBase.postDao().deletePost(post);
    }

    public int update(Post ... post) {
        return mAppDataBase.postDao().updatePost(post);
    }


}
